package z.t.b.db.data;

import java.math.BigDecimal;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * map工具类
 */
public final class MapUtils {

    /**
     *
     * @param map
     * @param key
     * @param def
     * @return
     */
    public static String getString(Map<String, Object> map, String key, String def) {
        Object value = getObject(map, key, def);
        return value instanceof String && value != null ? (String)value : def;
    }

    /**
     *
     * @param map
     * @param key
     * @param def
     * @return
     */
    public static Number getNumber(Map<String, Object> map, String key, Number def) {
        Object value = getObject(map, key, def);
        if (value instanceof Number && value != null) {
            return (Number)value;
        } else if (value != null && isNumber(value)) {
            BigDecimal number = new BigDecimal((String)value);
            return number;
        } else {
            return def;
        }
    }

    /**
     * 判断字符串是否是数值
     * @param value
     * @return
     */
    public static boolean isNumber(Object value) {
        if (value == null) {
            return false;
        } else if (value instanceof String) {
            if (value.toString().trim().length() == 0) {
                return false;
            } else {
//                String numberPress = "^(-?[1-9]\\d*\\.?\\d*)|(-?0\\.\\d*[1-9])|(-?[0])|(-?[0]\\.\\d*)$";
                //修改后
                String numberPress = "^(?:(-?[1-9]\\d*\\.?\\d*)|(-?0\\.\\d*[1-9])|(-?[0])|(-?[0]\\.\\d*))$";
                Pattern pattern = Pattern.compile(numberPress);
                Matcher match = pattern.matcher(value.toString());
                return match.matches();
            }
        } else {
            return false;
        }
    }

    /**
     *
     * @param map
     * @param keyName
     * @param value
     */
    public static void putObject(Map map, String keyName, Object value) {
        if (map != null) {
            if (value == null) {
                map.remove(keyName);
            } else {
                map.put(keyName, value);
            }

        }
    }

    /**
     *
     * @param map
     * @param keyName
     * @param defValue
     * @return
     */
    public static Object getObject(Map map, String keyName, Object defValue) {
        if (map == null) {
            return defValue;
        } else {
            Object value = map.get(keyName);
            if (value instanceof Object && value != null) {
                return value;
            } else {
                return defValue;
            }
        }
    }
}
